package com.ph.permission.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.agent.entity.Agent;
import com.ph.shopping.facade.member.dto.PayPasswordDto;
import com.ph.shopping.facade.member.entity.TradersPassword;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.merchant.entity.Merchant;
import com.ph.shopping.facade.permission.entity.User;
import com.ph.shopping.facade.permission.service.ISafeManageService;
import com.ph.shopping.facade.permission.service.IUserService;
import com.ph.shopping.facade.permission.vo.SessionRoleVo;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.supplier.entity.Supplier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

/**
 * @项目：phshopping-api-platform
 * @描述：安全管理controller
 * @作者： ShuHao
 * @创建时间：2017年3月30日
 * @Copyright @2017 by ShuHao
 */
@Controller
@RequestMapping("api/safeManage")
public class SafeManageController extends BaseController {

    @Reference(version = "1.0.0")
    private IUserService iUserService;

    @Reference(version = "1.0.0")
    private IMemberService iMemberService;

    @Reference(version = "1.0.0", timeout = 30000)
    private ISmsCodeSendService iSmsCodeSendService;

    @Reference(version = "1.0.0")
    private ISafeManageService iSafeManageService;

    /**
     * 跳转到账户安全管理页面
     *
     * @return
     */
    @RequestMapping(value = "/safeManagePage", method = RequestMethod.GET)
    public Object safeManagePage(String pay) {
        try {
            ModelAndView mv = new ModelAndView("/account/safeManage/safeManage");
            SessionUserVo sessionUserVo = getLoginUser();
            mv.addObject("sessionUserVo", sessionUserVo);
            mv.addObject("pay", pay);
            return mv;
        } catch (Exception e) {
            logger.error("获取登录者信息异常:", e.getMessage());
            return "";
        }
    }

    /**
     * 修改登录密码
     *
     * @return
     */
    @RequestMapping(value = "/updatePass", method = RequestMethod.POST)
    @ResponseBody
    public Object updatePass(User user, String newPassword, String verificationCode) {
        SessionUserVo sessionUserVo = getLoginUser();
        //MD5加密
        newPassword = MD5.getMD5Str(newPassword);
        //校验验证码
        Result result = iSmsCodeSendService.verifySmsCode(sessionUserVo.getTelphone(), SmsCodeType.SAFEMANAGE_CODE.getCodeType(), verificationCode);
        if ("200".equals(result.getCode())) {
            if (sessionUserVo.getId().equals(user.getId())) {
                user.setPassword(newPassword);
                return iUserService.updatePassword(user);
            } else {
                return getResult(ResultEnum.USER_ERROR);
            }
        } else {
            return getResult(ResultEnum.CHECKBIND_EXCEPTION);
        }
    }

    /**
     * 修改支付密码
     *
     * @return
     */
    @RequestMapping(value = "/updatePayPass", method = RequestMethod.POST)
    @ResponseBody
    public Object updatePayPass(TradersPassword tradersPassword, String verificationCode) {

        //获取当前用户
        SessionUserVo sessionUserVo = getLoginUser();
        Long sessionId = sessionUserVo.getId();
        //MD5加密
       /* tradersPassword.setPayPwd(MD5.getMD5Str(tradersPassword.getPayPwd()));*/


        //校验验证码
        Result resultMsg = iSmsCodeSendService.verifySmsCode(sessionUserVo.getTelphone(), SmsCodeType.SAFEMANAGE_CODE.getCodeType(), verificationCode);
        if (!"200".equals(resultMsg.getCode())) {
            return getResult(ResultEnum.CHECKBIND_EXCEPTION);
        }


        //判断页面传入id是否是当前登录者
        if (sessionId.equals(tradersPassword.getId())) {

            //判断是否有支付密码
            PayPasswordDto payPasswordDto = new PayPasswordDto();
            payPasswordDto.setCustomerType(2);
            payPasswordDto.setRelatedId(sessionId);
            Result result = iMemberService.getPayPwdInfo(payPasswordDto);

            if (result.getData() != null) {

                //修改
                payPasswordDto.setNewPassword(tradersPassword.getPayPwd());
                payPasswordDto.setUpdateUser(sessionId);
                return iMemberService.updatePayPassword(payPasswordDto);
            } else {

                //新增
                tradersPassword.setRelatedId(sessionId);
                tradersPassword.setCustomerType(2);
                tradersPassword.setCreateUser(sessionId);
                tradersPassword.setCreateTime(new Date());
                tradersPassword.setUpdateTime(new Date());
                tradersPassword.setUpdateUser(sessionId);
                tradersPassword.setId(null);
                return iMemberService.addMemberPayPwd(tradersPassword);
            }
        } else {
            return getResult(ResultEnum.USER_ERROR);
        }


    }

    /**
     * 修改手机号
     *
     * @return
     */
    @RequestMapping(value = "/updateTel", method = RequestMethod.POST)
    @ResponseBody
    public Object updateTel(User user, String verificationCode) {
        //获取当前用户
        SessionUserVo sessionUserVo = getLoginUser();
        //获取角色信息
        SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
        Long sessionId = sessionUserVo.getId();
        //MD5加密
        user.setPassword(MD5.getMD5Str(user.getPassword()));

        try {

            //检查是否为新手机号
            if (sessionUserVo.getTelphone().equals(user.getTelphone())) {
                return getResult(ResultEnum.CHECK_TEL_EXCEPTION);
            }

            //校验验证码
            Result resultMsg = iSmsCodeSendService.verifySmsCode(user.getTelphone(), SmsCodeType.SAFEMANAGE_CODE.getCodeType(), verificationCode);
            if (!"200".equals(resultMsg.getCode())) {
                return getResult(ResultEnum.CHECKBIND_EXCEPTION);
            }

            if (sessionId.equals(user.getId())) {
                User checkUser = new User();
                checkUser.setId(sessionId);
                Result result = iUserService.queryUser(checkUser);
                if (result.getData() != null) {
                    User user1 = (User) result.getData();
                    if (user1.getPassword().equals(user.getPassword())) {
                        //设置后台用户的电话号码
                        SetVal(sessionUserVo.getId(), user.getTelphone(), sessionRoleVo.getRoleCode());
                        //设置用户的电话号码
                        Result result1 = iUserService.updateUser(user);
                        if (!"200".equals(result1.getCode())) {
                            //回滚
                            SetVal(sessionUserVo.getId(), sessionUserVo.getTelphone(), sessionRoleVo.getRoleCode());
                        }
                        return result1;
                    } else {
                        return getResult(ResultEnum.MEMBER_PWD_MISMATCH);
                    }
                } else {
                    return getResult(ResultEnum.USER_ERROR);
                }
            } else {
                return getResult(ResultEnum.USER_ERROR);
            }
        } catch (Exception e) {
            //回滚
            SetVal(sessionUserVo.getId(), sessionUserVo.getTelphone(), sessionRoleVo.getRoleCode());
            logger.error("修改手机号异常:", e.getMessage());
            return getResult(ResultEnum.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * @return
     * @发送验证码
     */
    @RequestMapping(value = "/sendValidCode", method = RequestMethod.POST)
    @ResponseBody
    public Object sendValidCode() {

        return iSmsCodeSendService.sendSmsCodeByNoMsg(getLoginUser().getTelphone(), SmsCodeType.SAFEMANAGE_CODE.getCodeType());

    }

    /**
     * @return
     * @发送新手机号验证码
     */
    @RequestMapping(value = "/sendTelValidCode", method = RequestMethod.POST)
    @ResponseBody
    public Object sendTelValidCode(String tel) {
        if (tel != null && !"".equals(tel)) {
            return iSmsCodeSendService.sendSmsCodeByNoMsg(tel, SmsCodeType.SAFEMANAGE_CODE.getCodeType());
        }
        return getResult(ResultEnum.USER_ERROR);
    }

    public void SetVal(Long id, String tel, Byte code) {
        if (2 == code) {
            Supplier supplier = new Supplier();
            supplier.setId(id);
            supplier.setPersonTel(tel);
            iSafeManageService.updateSupplier(supplier);
        } else if (6 == code) {
            Merchant merchant = new Merchant();
            merchant.setId(id);
            merchant.setMerchantTel(tel);
            iSafeManageService.updateMerchant(merchant);
        } else if (3 == code || 4 == code || 5 == code) {
            Agent agent = new Agent();
            agent.setId(id);
            agent.setPersonTel(tel);
            iSafeManageService.updateAgent(agent);
        }
    }



}
